<template>
    <div class="add-btn">
        <el-dialog title="编辑用户" :visible.sync="dialogVisible" width="1200px" :append-to-body="true"
            @close="closeAddDialog" :close-on-click-modal="false">
            <el-form class="form-style" :model="editForm" :rules="rules" ref="refAddForm" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item size="small" prop="username" label="用户名">
                            <el-input clearable maxlength="18" v-model="editForm.username" placeholder="请输入"
                                oninput="value=value.replace(/\s*/g,'')" @blur="editForm.username = $event.target.value"
                                style="width: 100%"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item size="small" prop="roleId" label="角色">
                            <el-select v-model="editForm.roleId" placeholder="请选择" @change="roleChange"
                                style="width: 100%">
                                <el-option v-for="item in roleList" :key="item.id" :label="item.description"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item size="small" label="权限配置" style="width: 100%;" class="orgfrom">
                    <div class="content-box">
                        <div class="container">
                            <div class="content">
                                <Tree ref="refTree" @toggleOrgId="toggleOrgId" :dataList="dataList"></Tree>
                            </div>
                        </div>
                        <div class="container">
                            <div class="header" style="height: 50px">
                                <div class="header_left">
                                    <span v-if="roleName == 'ORG_ADMIN'">目前单位权限：{{ dataList.length }}</span>
                                    <span v-else>目前单位权限：{{ recordDataList.length }}</span>
                                </div>
                                <div class="header_right">
                                </div>
                            </div>
                            <!-- 机构 -->
                            <div class="content" v-show="roleName === 'ORG_ADMIN'">
                                <el-table :data="dataList" class="table" height="350px" row-key="id"
                                    :header-cell-style="headerStyle">
                                    <el-table-column align="center" prop="orgName" label="单位名称" show-overflow-tooltip>
                                    </el-table-column>
                                    <el-table-column align="center" prop="parentName" label="所属机构"
                                        show-overflow-tooltip>
                                    </el-table-column>
                                </el-table>
                            </div>
                            <!-- 装维多选 -->
                            <div class="content" v-show="roleName === 'INSTERALL_USER'">
                                <el-table :data="dataList" class="table" height="350px" row-key="id" ref="refTable1"
                                    :header-cell-style="headerStyle" @selection-change="batchSelect">
                                    <el-table-column width="50" align="center" type="selection"
                                        :reserve-selection="true"></el-table-column>
                                    <el-table-column align="center" prop="orgName" label="单位名称" show-overflow-tooltip>
                                    </el-table-column>
                                    <el-table-column align="center" prop="parentName" label="所属机构"
                                        show-overflow-tooltip>
                                    </el-table-column>
                                </el-table>
                            </div>
                            <!-- 联网单位 单选 -->
                            <div class="content" v-show="roleName === 'UNIT_ADMIN'">
                                <el-table :data="dataList" class="table" height="350px" row-key="id"
                                    :header-cell-style="headerStyle">
                                    <el-table-column label="" width="50" align="center">
                                        <template slot-scope="scope">
                                            <el-radio v-model="currentFactor" :label="scope.row.id"
                                                @input="clickChange">{{
                                                    "" }}</el-radio>
                                        </template>
                                    </el-table-column>
                                    <el-table-column align="center" prop="orgName" label="单位名称" show-overflow-tooltip>
                                    </el-table-column>
                                    <el-table-column align="center" prop="parentName" label="所属机构"
                                        show-overflow-tooltip>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeAddDialog" class="cancel-button">取 消</el-button>
                <el-button size="small" @click="addSubmit" v-preventReClick="1000" class="confirm-button">确
                    定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { handleTree, transTree } from "@utils/trans-tree";
import { userAssign, reqOrgList, reqOrgByUserId } from "@/api/api";
import { validateUsername, validatePass, validMobile } from "@utils/validate";
import { mapState } from "vuex";
import mixinPwd from "@utils/mixin/PreBrowserDefaultPassPop";
import treeselect from "@riophae/vue-treeselect"; //树形选择器
import "@components/vue-treeselect.less"; //树形选择器
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import Tree from "@/components/tree/orgUnit";

export default {
    name: "addUser",
    props: ["roleList", 'editRowInfo'],
    mixins: [mixinPwd, tableStyleMixin],
    components: { treeselect, Pagination, Tree },
    data() {
        return {
            normalizer(node) {
                return {
                    id: node.id,
                    label: node.orgName,
                    children: node.children,
                };
            },
            expandedKeys: false,
            page: 1,
            limit: 5,
            total: 0,
            // orgIdList:[],//组织机构id集
            isRadio: false,
            dialogVisible: false, //弹框是否显示
            // 新增用户信息数据
            editForm: {
                userId: "",
                username: "",
                roleId: "", // 角色id
                orgIdList: [], //组织机构id集
            },
            rules: {
                username: [
                    {
                        required: true,
                        message: "请输入用户名",
                        trigger: "blur",
                    },
                    {
                        validator: validateUsername,
                    },
                ],
                roleId: [
                    {
                        required: true,
                        message: "请选择角色",
                        trigger: ["blur", "change"],
                    },
                ],
                orgId: [
                    {
                        required: true,
                        message: "请选择组织机构",
                        trigger: ["blur", "change"],
                    },
                ],
            },
            isThreeTeams: window.sessionStorage.getItem("threeTeams"),
            loadingSearch: false,
            orgName: "",
            defaultProps: {
                children: "children",
                label: "orgName",
                isLeaf: "hasChildren",
                id: "id",
            },
            treeData: [],
            // 选择的数据
            iconId: "",
            parentCheckedId: 0,
            typeId: 0,
            // 选择的数据
            parentIdList: [],
            isTree: true,
            dataList: [],
            roleName: "ORG_ADMIN",
            recordDataList: [],
            selectedRow: null,
            currentFactor: "",
            orgList: [],
        };
    },
    computed: {
        ...mapState(["companyId", "user"]),
    },
    watch: {
        dialogVisible(val) {
            if (val) {
                this.updateOrg();
                //   console.log(this.editRowInfo,'editRowInfo');
                this.editForm.id = this.editRowInfo.id
                // this.editForm.orgIdList=this.editRowInfo.id
                this.editForm.roleId = this.editRowInfo.role.id
                this.editForm.username = this.editRowInfo.username
                this.roleName = this.editRowInfo.role.name
                this.getOrgByUserId() // 查询用户单位
            }
        },
    },
    methods: {
        // 查询用户单位
        async getOrgByUserId() {
            const res = await reqOrgByUserId(this.editRowInfo.id);
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.orgList = res.data.rows;
            console.log(this.orgList, 'orgList');
            if (this.editRowInfo.role.name == 'ORG_ADMIN') {
                this.$nextTick(() => {
                    this.$refs.refTree.getInfo(this.orgList[0].id)
                })
            } else if (this.editRowInfo.role.name == 'UNIT_ADMIN') {
                this.$nextTick(() => {
                    this.$refs.refTree.getInfo(this.orgList[0].parentId)
                })
                this.recordDataList = [this.orgList[0]]
                this.currentFactor = this.orgList[0].id
            }
            else if (this.editRowInfo.role.name == 'INSTERALL_USER') {
                this.$nextTick(() => {
                    this.$refs.refTree.getInfo(this.orgList[0].parentId)
                    // this.defaultCheckedKeys=this.orgList.map(item => item.id);
                    // console.log(this.defaultCheckedKeys,'this.defaultCheckedKeys');
                    this.recordDataList = this.orgList;
                    this.orgList.forEach((item) => {
                        // const row = this.dataList.find((data) => data.id === item.id);
                        this.$refs.refTable1.toggleRowSelection(item, true); // 选中该行
                    });
                })
            }
        },
        clickChange(row) {
            //   console.log(row,'row')//这个打印的就是选中的这一条数据
            this.recordDataList = [row]
        },
        batchSelect(selection) {
            // console.log("batchSelect", selection);
            let batchDataList = selection;
            this.recordDataList = batchDataList;
        },
        // 切换机构
        toggleOrgId(data) {
            this.parentId = data.orgId;
            this.getDataList();
        },
        async getDataList() {
            const res = await reqOrgList({
                userId: this.user.userId,
                roleName: this.user.roleName,
                tenantId: this.user.tenantId,
                orgName: '',
                parentId: this.parentId,
                type: "4"
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.dataList = res.data.rows;
            this.total = res.data.total;
        },
        // 更新整个单位
        updateOrg() {
            this.isTree = false;
            setTimeout(() => {
                this.isTree = true;
            }, 0);
        },
        // 单选（限制多选）
        selected(selection, row) {
            // console.log(selection, row);
            if (selection.length <= 0) this.editForm.orgIdList = []; //如果取消了勾选则清空数组
            if (this.editForm.roleId === "") {
                this.$refs.refTable.clearSelection();
                this.$modal.notifyWarning("请先选择角色");
                return;
            }
            // 组织机构只能单选
            if (this.isRadio) {
                if (selection.length === 1) {
                    this.editForm.orgIdList = [row.id];
                } else if (selection.length > 1) {
                    this.editForm.orgIdList = [];
                    this.$refs.refTable.clearSelection();
                    this.$refs.refTable.toggleRowSelection(selection.pop());
                    // this.$nextTick(() => {
                    this.editForm.orgIdList = [row.id];
                    // });
                }
            }
        },
        getSimpleCheckedNodeIds(originData) {
            // 定义数组
            const checkedNodeIds = [];
            // 判断是否为全选，若为全选状态返回被选中的父节点数据，不为全选状态正常返回被选中的子节点的数据
            const isAllChecked = function (node) {
                const childNodes = node.root ? node.root.childNodes : node.childNodes;
                childNodes.forEach((child) => {
                    console.log(child, "child");
                    if (child.checked) {
                        checkedNodeIds.push(child.data);
                    }
                    if (child.indeterminate) {
                        isAllChecked(child);
                    }
                });
            };
            isAllChecked(originData);
            console.log(checkedNodeIds, "checkedNodeIds");
            return checkedNodeIds;
        },
        getCurrentNode(e) {
            console.log(e, "eee");
        },
        // 限制全选按钮
        selectAll() {
            if (this.editForm.roleId === "") {
                this.$refs.refTable.clearSelection();
                this.$modal.notifyWarning("请先选择角色");
                return;
            }
        },
        // select获取组织机构id  多选
        handleSelectionChange(val) {
            // console.log(val);
            if (this.isRadio) return; //如果是单选，则不走下面，以免搞乱
            this.editForm.orgIdList = [];
            let that = this;
            val.forEach((e) => {
                that.editForm.orgIdList.push(e.id);
            });
            this.editForm.orgIdList = [...new Set(this.editForm.orgIdList)];
        },
        // 角色选择：限制单选多选  如果是组织机构人员，则单选
        roleChange(val) {
            this.$refs.refTable1.clearSelection();//清空复选框
            // console.log(val);
            this.roleList.forEach(item => {
                if (item.id == val) {
                    this.roleName = item.name
                }
            })
            this.currentFactor = ''
            this.recordDataList = []
        },
        // 点击获取图形验证码
        async reqVerification() {
            const res = await reqImageCode();
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.$nextTick(() => {
                this.imageCodeSrc = res.data.imageCode;
            });
        },
        // 点击获取手机验证码
        async getSmsCode() {
            let { mobile, imageCode } = this.editForm;
            const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
            if (!mobile) return this.$modal.notifyWarning("请先填写手机号");
            if (!reg.test(mobile))
                return this.$modal.notifyWarning("请输入正确的手机号");
            if (!imageCode) return this.$modal.notifyWarning("请先填写图形验证码");
            const res = await reqSmsCode({
                imageCode: this.editForm.imageCode,
                mobile: this.editForm.mobile,
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.$modal.notifyWarning("请注意查收手机短信验证码");
            this.showCountDown = false;
            this.countDown = 60;
            this.isNext = false;
            let intervalId = setInterval(() => {
                if (this.countDown > 0 && this.countDown <= 60) {
                    this.countDown--;
                } else {
                    this.showCountDown = true;
                    clearInterval(intervalId);
                    intervalId = null;
                }
            }, 1000);
        },
        addSubmit() {
            this.$refs.refAddForm.validate(async (valid) => {
                if (!valid) return;
                // 机构
                if (this.roleName === "ORG_ADMIN") {
                    const res = await userAssign({
                        userId: this.editForm.id,
                        username: this.editForm.username,
                        roleId: this.editForm.roleId,
                        tenantId: this.user.tenantId,
                        orgIdList: [this.parentId],
                    });
                    if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                    this.$modal.notifySuccess("编辑用户成功");
                    this.$parent.userList(); //更新用户列表
                    this.closeAddDialog();
                } else if (this.roleName == "INSTERALL_USER") {
                    // 装维
                    if (this.recordDataList.length == 0) return this.$modal.notifyWarning('请选择单位');
                    const res = await userAssign({
                        userId: this.editForm.id,
                        username: this.editForm.username,
                        roleId: this.editForm.roleId,
                        tenantId: this.user.tenantId,
                        orgIdList: this.recordDataList.map(item => item.id),
                    });
                    if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                    this.$modal.notifySuccess("编辑用户成功");
                    this.$parent.userList(); //更新用户列表
                    this.closeAddDialog();
                } else if (this.roleName == "UNIT_ADMIN") {
                    if (this.recordDataList.length == 0) return this.$modal.notifyWarning('请选择单位');
                    // 联网单位管理员
                    const res = await userAssign({
                        userId: this.editForm.id,
                        username: this.editForm.username,
                        roleId: this.editForm.roleId,
                        tenantId: this.user.tenantId,
                        orgIdList: [this.currentFactor],
                    });
                    if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                    this.$modal.notifySuccess("编辑用户成功");
                    this.$parent.userList(); //更新用户列表
                    this.closeAddDialog();
                }
            });
        },
        // 点击取消和关闭按钮 （ 清除验证  关闭弹窗）
        closeAddDialog() {
            this.roleName = "ORG_ADMIN";
            this.$refs.refAddForm.resetFields();
            this.dialogVisible = false;
            if (this.$refs.refTable1) {
                this.$refs.refTable1.clearSelection();//清空勾选
            }
        },
    },
    deactivated() {
        if (this.$refs.refTable != null || this.$refs.refAddForm != null) {
            this.closeAddDialog();
        }
    },
};
</script>

<style lang="less" scoped>
@import url("~@views/style/tablePage.less");
@import url("../../common.less");

.form-style {
    width: 100%;
}

/deep/ .el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
    margin-bottom: 26px;
}

// 分页器
::v-deep .el-pager {
    border-radius: 30px;
    background: @paginationBgcolor;
    margin: 0 5px;
    height: 32px;
}

::v-deep .el-pager li {
    min-width: 32px !important;
    background: @paginationBgcolor !important;
    color: #b4b7bd !important;
    height: 32px !important;
    line-height: 32px !important;
}

::v-deep .el-pager li.active {
    color: #fff !important;
    border-radius: 30px !important;
    background: #7367f0 !important;
}

::v-deep .el-pager li:first-child {
    border-radius: 30px !important;
}

::v-deep .el-pager li:last-child {
    border-radius: 30px !important;
}

::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background: #7367f0 !important;
}

::v-deep .el-tree {
    height: 100%;
    font-size: 14px;
    background: @primaryHeaderBgcolor;
    box-sizing: border-box;
    padding: 12px 10px;
    color: @primaryThemeTxtColor;
    overflow: hidden;
    overflow-y: scroll;
}

::v-deep .el-tree-node__content {

    // padding: 5px 0 !important;
    &:hover {
        background: @paginationBgcolor !important;
        border-radius: 4px;
    }
}

::v-deep .el-tree-node.is-focusable>.el-tree-node__content {
    padding: 5px 0;
}

// 解决收起后白色背景问题
::v-deep .el-tree-node.is-expanded>.el-tree-node__content {
    background-color: transparent;
}

// 解决展开后白色背景问题
::v-deep .el-tree-node.is-focusable>.el-tree-node__content {
    background-color: transparent;
    border-radius: 4px;
}

::v-deep .is-current>.el-tree-node__content>.el-tree-node__label {
    color: #f0f0f0;
}

.ogText {
    color: @primaryThemeTxtColor2;
}

::v-deep .orgfrom .el-form-item__content {
    width: 91.5% !important;
}

.content-box {
    width: 100%;
    display: flex;
    justify-content: space-between;

    .container {
        // flex: 1;
        width: 49%;
        height: 400px;
        overflow-y: auto;
        border: 1px solid #999;
        border-radius: 5px;

        .header {
            color: @primaryTxtcolor;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
    }
}

// 单选按钮
::v-deep .el-radio__input.is-checked .el-radio__inner {
    border-color: #7367f0;
    background: #7367f0;
}
</style>